using System;
using Hive.Core.Common.Shell;

namespace Hive.Core.Model.Commands
{
    /// <summary>
    /// Adds a binary repository mapping to an existing hive.
    /// </summary>
    public class AddBinaryRepositoryMappingCommand : BaseHiveCommand
    {
        private readonly BinaryRepositoryConfiguration.Mapping mapping;

        /// <summary>
        /// Initializes the command.
        /// </summary>
        /// <param name="mapping">The mapping to add.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="mapping"/> is null.</exception>
        public AddBinaryRepositoryMappingCommand(BinaryRepositoryConfiguration.Mapping mapping)
        {
            if (mapping == null)
                throw new ArgumentNullException("mapping");

            this.mapping = mapping;
        }

        /// <inheritdoc />
        protected override CommandExitCode ExecuteWithHive(IHiveManager hiveManager, IShell shell, IHive hive)
        {
            var newHiveConfiguration = (HiveConfiguration) hive.Configuration.Copy();
            newHiveConfiguration.BinaryRepositoryConfiguration.AddMapping(mapping);

            hiveManager.Reconfigure(hive.Directory, newHiveConfiguration);
            return CommandExitCode.Success;
        }
    }
}